package com.donleo.security.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donleo.common.api.CommonResult;
import com.donleo.common.model.Role;
import com.donleo.common.relation.RolePermissionRelation;
import com.donleo.common.relation.UserRoleRelation;
import com.donleo.security.mapper.RoleMapper;
import com.donleo.security.mapper.RolePermissionRelationMapper;
import com.donleo.security.mapper.UserRoleRelationMapper;
import com.donleo.security.service.RoleService;
import com.donleo.security.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author liangd
 * @since 2020-12-21
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;

    @Autowired
    private RolePermissionRelationMapper rolePermissionRelationMapper;


    @Override
    public CommonResult add(Role role) {
        role.setCreateTime(new Date());
        int count = roleMapper.insert(role);
        if (count == 1) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult delete(Integer id) {

        Role role = roleMapper.selectById(id);
        List<UserRoleRelation> list = new LambdaQueryChainWrapper<>(userRoleRelationMapper)
                .eq(UserRoleRelation::getRoleCode, role.getCode())
                .list();
        List<RolePermissionRelation> list1 = new LambdaQueryChainWrapper<>(rolePermissionRelationMapper)
                .eq(RolePermissionRelation::getRoleCode, role.getCode())
                .list();
        if (list.size() > 0) {
            return CommonResult.failed();
        }
        if (list1.size() > 0) {
            return CommonResult.failed();
        }
        int count = roleMapper.deleteById(id);
        return CommonResult.success(count);
    }

    @Override
    public CommonResult updateRole(Role role) {
        role.setUpdateTime(new Date());
        int count = roleMapper.updateById(role);
        if (count == 1) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public Role findById(Integer id) {
        return roleMapper.selectById(id);
    }

    @Override
    public List<Role> findAll(RoleVo roleVo) {
        return roleMapper.findAll(roleVo);
    }

    @Override
    public long getCount(RoleVo roleVo) {
        return roleMapper.getCount(roleVo);
    }

}
